<template>
  <view class="user-detail-container">
    <!-- 页面头部 -->
    <view class="header" :style="currentGradient">
      <text class="title">编辑个人资料</text>
    </view>

    <!-- 用户信息表单 -->
    <view class="user-form">
      <!-- 头像 -->
      <view class="avatar-section">
        <button
          v-if="isWechatEnv"
          open-type="chooseAvatar"
          @chooseavatar="onChooseAvatar"
          class="avatar-button"
        >
          <image
            :src="userInfo.avatar"
            mode="aspectFill"
            class="avatar-image"
          />
          <text class="avatar-tip">点击更换头像</text>
        </button>

        <!-- App和H5环境 -->
        <view v-else class="avatar-button" @click="onAvatarClick">
          <image
            :src="userInfo.avatar"
            mode="aspectFill"
            class="avatar-image"
          />
          <text class="avatar-tip">点击更换头像</text>
        </view>
      </view>

      <!-- 姓名 -->
      <view class="form-item">
        <text class="label">姓名</text>
        <input
          v-model="userInfo.realName"
          placeholder="请输入姓名"
          class="input"
          maxlength="20"
        />
      </view>

      <!-- 昵称 -->
      <view class="form-item">
        <text class="label">昵称</text>
        <input
          v-model="userInfo.nickname"
          placeholder="请输入昵称"
          class="input"
          maxlength="20"
        />
      </view>

      <!-- 手机 -->
      <view class="form-item">
        <text class="label">手机</text>
        <text class="input read-only">{{ userInfo.mobile || "未绑定" }}</text>
      </view>

      <!-- 性别 -->
      <view class="form-item">
        <text class="label">性别</text>
        <radio-group @change="onGenderChange" class="radio-group">
          <label class="radio-label">
            <radio
              value="0"
              :checked="userInfo.sex === 0"
              :color="currentTheme.primary"
            />
            男
          </label>
          <label class="radio-label">
            <radio
              value="1"
              :checked="userInfo.sex === 1"
              :color="currentTheme.primary"
            />
            女
          </label>
        </radio-group>
      </view>
    </view>

    <!-- 保存按钮 -->
    <button class="save-btn" :style="currentGradient" @click="saveUserInfo">
      保存信息
    </button>
  </view>
</template>

<script setup lang="ts">
import { reactive, onMounted, computed } from "vue";
import { modify, getUserProfile } from "@/api/userApi";
import { uploadFile } from "@/api/common";
import { getCurrentTheme } from "@/utils/theme";

// 用户信息数据
const userInfo = reactive({
  id: 0,
  nickname: "",
  avatar: "/static/images/avatar.png",
  mobile: "",
  sex: 0,
  point: 0,
  experience: "",
  level: 0,
  brokerageEnabled: 0,
});

// 获取当前主题
const currentTheme = computed(() => getCurrentTheme());

// 计算当前主题的渐变样式
const currentGradient = computed(() => {
  return `background: linear-gradient(135deg, ${currentTheme.value.start} 0%, ${currentTheme.value.end} 100%);`;
});

// 判断运行环境
const isWechatEnv = computed(() => {
  // #ifdef MP-WEIXIN
  return true;
  // #endif
  return false;
});

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo();
});

// 加载用户信息
const loadUserInfo = async (forceUpdate = false) => {
  uni.showLoading({ title: "加载中..." });
  try {
    const storedUserInfo = uni.getStorageSync("userInfo");
    if (storedUserInfo && storedUserInfo.id) {
      // 直接使用本地存储的数据更新界面
      const userData = {
        ...storedUserInfo,
      };
      Object.assign(userInfo, userData);

      // 如果强制更新，则调用接口获取最新数据
      if (forceUpdate) {
        const res = await getUserProfile();
        if (res.code === 0) {
          const userData = {
            ...res.data,
          };
          Object.assign(userInfo, userData);
          // 更新本地存储
          uni.setStorageSync("userInfo", userData);
        } else {
          uni.showToast({ title: res.msg || "获取用户信息失败", icon: "none" });
        }
      }
    } else {
      uni.showToast({ title: "请先登录", icon: "none" });
    }
  } catch (err) {
    uni.showToast({ title: "获取用户信息失败", icon: "none" });
  } finally {
    uni.hideLoading();
  }
};

// 微信环境下的头像选择
const onChooseAvatar = async (e: any) => {
  console.log("微信头像选择回调:", e);
  const tempAvatarPath = e.detail.avatarUrl;

  if (!tempAvatarPath) {
    uni.showToast({ title: "未选择头像", icon: "none" });
    return;
  }

  console.log("选择的头像临时路径:", tempAvatarPath);

  // 从本地缓存获取 token
  const storedUserInfo = uni.getStorageSync("userInfo");
  const token = uni.getStorageSync("token");

  if (!token) {
    uni.showToast({ title: "请先登录", icon: "none" });
    return;
  }

  uploadAvatarImage(tempAvatarPath);
};

// 非微信环境下的头像点击事件
const onAvatarClick = async () => {
  console.log("非微信环境头像点击");
  await chooseImage();
};

// App和H5环境下的图片选择
const chooseImage = () => {
  // #ifdef APP-PLUS
  // 强制请求权限
  plus.android.requestPermissions([
    "android.permission.CAMERA",
    "android.permission.READ_EXTERNAL_STORAGE",
  ]);
  // #endif

  // 直接使用回调方式，避免async/await可能的问题
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: function (res) {
      if (res.tempFilePaths && res.tempFilePaths.length > 0) {
        const tempAvatarPath = res.tempFilePaths[0];
        const token = uni.getStorageSync("token");

        if (!token) {
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        uploadAvatarImage(tempAvatarPath);
      }
    },
    fail: function (err) {
      console.error("选择图片失败:", err);
      uni.showToast({ title: "选择图片失败", icon: "none" });
    },
  });
};

// 上传头像图片的通用方法
const uploadAvatarImage = async (tempAvatarPath: string) => {
  console.log("开始上传头像:", tempAvatarPath);
  uni.showLoading({ title: "上传中..." });

  try {
    // 调用 common.ts 中的 uploadFile 方法
    const result = await uploadFile(tempAvatarPath, "avatar");

    console.log("上传成功，返回数据:", result);

    if (result.code === 0) {
      // 服务器返回成功，获取头像URL
      const avatarUrl = result.data || tempAvatarPath;

      // 调用 modify 接口更新用户头像
      const storedUserInfo = uni.getStorageSync("userInfo");
      const updateData = {
        ...storedUserInfo,
        avatar: avatarUrl,
      };

      const modifyResult = await modify(updateData);

      if (modifyResult.code === 0) {
        // 更新成功，处理上传成功
        handleUploadSuccess(avatarUrl, "上传成功");
      } else {
        // 更新失败，但仍然更新本地显示
        handleUploadSuccess(avatarUrl, "上传完成");
      }
    } else {
      // 服务器返回失败，但仍然更新本地显示
      handleUploadSuccess(tempAvatarPath, "上传完成");
    }
  } catch (err) {
    console.error("上传失败:", err);
    // 即使失败也更新头像（用本地图片）
    handleUploadSuccess(tempAvatarPath, "操作完成");
  } finally {
    uni.hideLoading();
  }
};

// 处理上传成功
const handleUploadSuccess = (avatarUrl: string, message: string) => {
  userInfo.avatar = avatarUrl;
  const storedUserInfo = uni.getStorageSync("userInfo");
  uni.setStorageSync("userInfo", {
    ...storedUserInfo,
    avatar: userInfo.avatar,
  });
  uni.showToast({ title: message, icon: "success" });
};

// 性别变化事件
const onGenderChange = (e: any) => {
  console.log("性别变化:", e.detail.value);
  const index = parseInt(e.detail.value);
  userInfo.sex = index;
};

// 保存用户信息
const saveUserInfo = async () => {
  uni.showLoading({ title: "保存中..." });
  try {
    const storedUserInfo = uni.getStorageSync("userInfo");
    // 构造只包含必要字段的对象
    const userData = {
      ...storedUserInfo,
      avatar: userInfo.avatar,
      nickname: userInfo.nickname,
      sex: userInfo.sex,
    };

    const res = await modify(userData);
    if (res.code === 0) {
      // 更新本地存储的用户信息
      uni.setStorageSync("userInfo", userData);
      uni.showToast({ title: "保存成功", icon: "success" });
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    } else {
      uni.showToast({ title: res.msg || "保存失败", icon: "none" });
    }
  } catch (err) {
    uni.showToast({ title: "保存失败", icon: "none" });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style scoped lang="scss">
.user-detail-container {
  min-height: 100vh;
  padding: 20rpx;
  background-color: $background-color;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  border-radius: 20rpx;
  margin: 0 20rpx 40rpx;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: $uni-text-color-inverse;
  }
}

.user-form {
  background: $uni-bg-color;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin: 0 20rpx;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 50rpx;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid $uni-border-color;
}

.avatar-image {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  border: 3rpx solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.avatar-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: transparent;
  padding: 0;
  margin: 0;
  font-size: inherit;
  line-height: 1;
  border: none;
  cursor: pointer;
}

.avatar-button::after {
  border: none;
}

.avatar-tip {
  margin-top: 20rpx;
  font-size: 26rpx;
  color: $uni-text-color-grey;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 50rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid $uni-border-color;

  &:last-child {
    margin-bottom: 0;
    border-bottom: none;
  }
}

.label {
  width: 140rpx;
  font-size: 30rpx;
  color: $uni-text-color;
  font-weight: 500;
}

.input {
  flex: 1;
  font-size: 30rpx;
  color: $uni-text-color;
  padding: 15rpx 10rpx;
  border-bottom: 1rpx solid transparent;

  &.read-only {
    color: $uni-text-color-grey;
  }
}

.radio-group {
  display: flex;
  flex: 1;
}

.radio-label {
  margin-right: 50rpx;
  font-size: 30rpx;
  color: $uni-text-color;
  display: flex;
  align-items: center;

  radio {
    margin-right: 10rpx;
  }
}

.save-btn {
  width: 90%;
  height: 90rpx;
  color: $uni-text-color-inverse;
  font-size: 34rpx;
  font-weight: bold;
  border-radius: 50rpx;
  margin: 60rpx auto 40rpx;
  border: none;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  }
}
</style>
